@extends('layout.page')
@section('title','活动 - 新建')

@section('stylesheet')
    <link href="/css/plugins/steps/jquery.steps.css" rel="stylesheet">
    <link href="/css/plugins/datepicker/datepicker3.css" rel="stylesheet">
    <link href="/css/plugins/jqgrid/ui.jqgrid.css" rel="stylesheet">
    <link href="/css/plugins/webUploader/webuploader.css" rel="stylesheet">
    <link href="/css/plugins/webUploader/style33.css" rel="stylesheet">
    <style>
        .short {
            /*width: 150px;*/
            display: inline-block;
            text-align: center;
            padding: 5px 25px 5px 5px;
            margin: 5px;
            border-radius: 20%;
        }
    </style>
@endsection


@section('static-page')
        <div class="col-sm-12">
            <div class="ibox">
                <div class="ibox-content">
                    <form id="activity-form" method="POST" action="/ceb/activities/store"
                          class="wizard-big form-horizontal">
                        {{csrf_field()}}
                        <h1>基本信息</h1>
                        <fieldset style="position: relative;">
                            <div class="form-group">
                                <label class="control-label col-sm-2">活动名称</label>

                                <div class="col-sm-10">
                                    <input class="form-control required" id="activity-name" name="name" type="text">
                                </div>
                            </div>
                            <div class="hr-line-dashed"></div>
                            <div class="form-group">
                                <label class="control-label col-sm-2">活动时间</label>

                                <div class="input-daterange input-group col-sm-10" id="datepicker">
                                    <input readonly type="text" class="input-sm form-control _date" name="start_date"
                                           value="{{ date('Y-m-d') }}"/>
                                    <span class="input-group-addon"> —— </span>
                                    <input readonly type="text" class="input-sm form-control _date" name="end_date"
                                           value="{{ date('Y-m-d') }}"/>
                                </div>
                            </div>
                            <div class="hr-line-dashed"></div>
                            <div class="form-group">
                                <label class="control-label col-sm-2">banner图</label>

                                <div class="col-sm-10">
                                    <a id="upload-btn" class="btn btn-lg">上传图片</a>
                                    <div class="webuploader-thumb" id="img-thumb">
                                        <img width="100%">
                                    </div>
                                </div>
                                <input id="banner" name="banner" class="hidden" type="text">
                            </div>
                            <div class="hr-line-dashed"></div>
                            <div class="form-group">
                                <label class="control-label col-sm-2">活动规则</label>

                                <div class="col-sm-10">
                                    <textarea name="rules" class="form-control" rows="5"></textarea>
                                </div>
                            </div>
                            <div class="hr-line-dashed"></div>
                            <div class="form-group">
                                <label class="control-label col-sm-2">预期目标</label>

                                <div class="col-sm-10">
                                    <textarea name="purpose" class="form-control" rows="5"></textarea>
                                </div>
                            </div>

                        </fieldset>
                        <h1>活动对象</h1>
                        <fieldset style="position: relative;">

                            <div class="col-sm-12">
                                <div class="form-group">
                                    <div class="radio">
                                        <label><input type="radio" checked="" value="1" id="target1" name="filter_type">渠道</label>
                                        &nbsp;&nbsp;&nbsp;&nbsp;
                                        <label><input type="radio" value="2" id="target2" name="filter_type">群体</label>
                                    </div>
                                </div>
                            </div>
                            <div id="channel-block">
                                <div class="col-sm-2"></div>
                                <div class="col-sm-4 m-l-n">
                                    <select class="form-control" multiple="" id="channel_provider_list"
                                            name="channel_provider">
                                        @foreach($channel_provider_list as $channel_provider)
                                            <option value="{{$channel_provider->id}}">{{$channel_provider->name}}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-sm-2 m-l-n">
                                    <i class="ui-icon-arrow-1-ne icon"></i>
                                </div>
                                <div class="col-sm-4 m-l-n">
                                    <select class="form-control" multiple="" id="channel_list" name="">
                                    </select>
                                </div>
                                <div class="col-sm-2"></div>
                                <div class="col-sm-12" id="selected-channel"></div>
                                <div class="col-sm-12"><a class="btn btn-success hidden btn-get-users">确定</a></div>
                            </div>
                            <div id="group-block" class="hidden">
                                <div class="col-sm-10 m-l-n">
                                    <select class="form-control" id="group_list" name="user_group">
                                        @foreach($group_list as $group)
                                            <option value="{{$group->id}}">{{$group->name}}</option>
                                        @endforeach
                                    </select>

                                    <div class="col-sm-12" id="selected-group"></div>
                                    <div class="col-sm-12"><a class="btn btn-success btn-get-users">确定</a></div>
                                </div>
                            </div>
                            <div class="jqGrid_wrapper">
                                <table id="user-list"></table>
                                <div id="user-list-pager"></div>
                            </div>

                            <div id="selected-user-list"></div>
                        </fieldset>

                        <h1>活动奖励</h1>
                        <fieldset style="position: relative;">
                            <div class="form-group">
                                <label class="col-md-2 form-label">奖池名称</label>

                                <div class="col-sm-8">
                                    <input id="reward-keyword" class="form-control">
                                </div>
                                <div class="col-sm-2">
                                    <a class="btn btn-success" id="reward-search-btn">查询</a>
                                </div>
                            </div>
                            <div class="jqGrid_wrapper">
                                <table id="reward-list"></table>
                                <div id="reward-list-pager"></div>
                            </div>
                            <div id="selected-reward"></div>
                        </fieldset>
                    </form>
                </div>
            </div>
        </div>
@endsection

@section('javascript')
<script src="/js/plugins/datepicker/bootstrap-datepicker.js"></script>

<script src="/js/plugins/steps/jquery.steps.min.js"></script>
<script src="/js/plugins/jqgrid/i18n/grid.locale-cn.js"></script>
<script src="/js/plugins/jqgrid/jquery.jqGrid.min.js"></script>

<script src="/js/webuploader.min.js"></script>
<script>
    var channel_list = {!! $channel_list->toJson() !!};
    var behavior_list = {!! json_encode($behavior_list) !!};
    $.jgrid.defaults.styleUI = 'Bootstrap';
    var selected_user_map = {};
    var select_reward_map = {};
    var selected_channel_map = {};
    var user_jqgrid = new JqgridTable('#user-list', {
        colNames: ['ID', '手机号', '姓名', '操作'],
        colModel: [
            {
                name: 'uid',
                index: 'uid',
                width: 60,
                sorttype: "int"
            },
            {
                name: 'user_phone',
                index: 'user_phone',
                width: 180,
                sorttype: "int",
            },
            {
                name: 'real_name',
                index: 'real_name',
                width: 100
            },
            {
                name: 'action',
                index: 'action',
                width: 100
            }
        ],
        pager: "#user-list-pager"
    }, '/ceb/users/filters', 'POST');
    var reward_jqgrid = new JqgridTable('#reward-list', {
        colNames: ['奖池名称', '奖品', '行为', '操作'],
        colModel: [
            {
                name: 'name',
                index: 'name',
                width: 100,
            },
            {
                name: 'reward',
                index: 'reward',
                width: 200,
            },
            {
                name: 'behavior',
                index: 'behavior',
                width: 100
            },
            {
                name: 'action',
                index: 'action',
                width: 80
            }
        ],
        pager: "#reward-list-pager"
    }, '/ceb/rewardpackages/search', 'GET');


    function setTags(container, list, postName) {
        container = $(container).empty();
        $.each(list, function (k, v) {
            var s = '<div class="alert alert-success alert-dismissable short">' + v.name;
            if (postName) {
                s += '<input type="text" name="' + postName + '[]" value="' + v.value + '" class="hidden">';
            }
            s += '<button aria-hidden="true" data-dismiss="alert" class="close" type="button" data-value="' + v.value + '">×</button>' +
                    '</div>'
            container.append(s);
        });
    }

    function setUserGroup(){
        var id = $('#group_list').val();
        var name = $('#group_list option:selected').html();

        setTags('#selected-group', [{
            value:id,
            name:name
        }], 'group');

        $('#selected-group .close').on('click', function () {
            var value = $(this).data('value');
            $('option[value=' + value + ']', $(select)).get(0).selected = false;
        });
    }

    function resetUser() {
        var list = [];
        $.each(selected_user_map, function (k, v) {
            list.push(v);
        });
        setTags('#selected-user-list', list, 'ignore_user');
        $('#selected-user-list .close').on('click', function () {
            var value = $(this).data('value');
            delete selected_user_map[value];
            resetUser();
        });
    }


    function resetReward() {
        var list = obj_values(select_reward_map);
        setTags('#selected-reward', list, 'rewards');

        $('#selected-reward .close').on('click', function () {
            var id = $(this).data('value').split(',')[0];
            delete select_reward_map[id];
            resetReward();
        });
    }

    function resetChannels(){
        var list = obj_values(selected_channel_map);
        setTags('#selected-channel', list, 'channel');
        $('#selected-channel .close').on('click', function () {
            var id = $(this).data('value');
            delete selected_channel_map[id];
            resetChannels();
        });
        if (list.length > 0) {
            $('.btn-get-users').removeClass('hidden');
        } else {
            $('.btn-get-users').addClass('hidden');
        }
    }

    $(document).ready(function () {
//        $('#wizard').steps();
        var steps = $("#activity-form").steps({
            bodyTag: "fieldset",
            showFinishButtonAlways: false,
//            forceMoveForward:true,
            enableCancelButton: false,
            onStepChanging: function (event, currentIndex, newIndex) {
                return true;
            },
            onFinished: function (event, currentIndex) {
                var form = $(this);
                form.submit();
            }
        });

        var uploader = WebUploader.create({
            // 选完文件后，是否自动上传。
            auto: true,
            // swf文件路径
            swf: '/js/Uploader.swf',
            // 文件接收服务端。
            server: '/common/files/upload',
            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            fileNumLimit: 1,
            pick: {
                id: '#upload-btn',
                multiple: false,
            },
            // 只允许选择图片文件。
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image,image/gif,image/jpg,image/jpeg,image/bmp,image/png'
            },
//            sendAsBinary: true,
            method: "post",
        }).on('beforeFileQueued',function(file){
            if(file.Status == 'invalid'){
                return false;
            }
            this.reset();
        }).on('uploadSuccess', function (file, result) {
            if (result.code == 1) {
                $('#banner').val(result.data.src);
            } else {
                alert(result.message);
            }
        }).on('uploadBeforeSend', function (object, data, headers) {
            headers['X-XSRF-TOKEN'] = $.cookie('XSRF-TOKEN');
        }).on('fileQueued', function (file) {
            var $img = $('<img width="100%">');
            // $list为容器jQuery实例
            $('#img-thumb').html($img);
            // 创建缩略图
            // 如果为非图片文件，可以不用调用此方法。
            // thumbnailWidth x thumbnailHeight 为 100 x 100
            // 定义缩略图大小
            var _uploaderWidth = $(".webuploader-pick").width();
            var _uploaderHeight = $(".webuploader-pick").height();
            uploader.makeThumb(file, function (error, src) {
                if (error) {
                    $img.replaceWith('<div class="color-2 pt15 align-center" style="width:' + _uploaderWidth + 'px;">文件已经选择</div>');
                    return;
                }
                $img.attr('src', src);
            }, _uploaderWidth, _uploaderHeight);
        });


        setDateRange('input[name=start_date]', 'input[name=end_date]');

        $('input[name=filter_type]').on('change', function () {
            var val = $(this).val();
            if (val == 1) {
                $('#channel-block').removeClass('hidden');
                $('#group-block').addClass('hidden');
            } else {
                $('#channel-block').addClass('hidden');
                $('#group-block').removeClass('hidden');
            }
        });

        var channel_map = groupby(channel_list, 'channel_provider_id');
        var channel_container = $('#channel_list');
        $('#channel_provider_list').on('change', function () {
            var cp_id_list = $(this).val();
            channel_container.html('<option value="0">全部</option>');
            $.each(cp_id_list, function (k, id) {
                $.each(channel_map[id], function (k, channel) {
                    var option = document.createElement('option');
                    option.value = channel.id;
                    option.innerHTML = channel.code + '' + channel.no;
                    channel_container.append(option);
                });
            });
        });
        channel_container.on('click', function () {
            var id_list = $(this).val();
            if (id_list.indexOf("0") > -1 || id_list.indexOf(0) > -1) {
                $('option',channel_container).each(function () {
                    var val = $(this).val();
                    if (val != 0 && !(val in selected_channel_map)) {
                        selected_channel_map[val] = {
                            name: $(this).html(),
                            value: val
                        };
                    }
                });
            }else{
                var val = $(this).val(),
                        name = $('option:selected',$(this)).html();
                selected_channel_map[val] = {
                    name:name,
                    value:val
                }
            }
            resetChannels();
        });

        setUserGroup();
        $('#group_list').on('change', function(){
            setUserGroup();
        });

        $('.btn-get-users').on('click', function () {
            var filter_type = $('input[name=filter_type]:checked').val();
            var filter_list = [];
            if (filter_type == 1) {
                filter_list = $('#channel_list').val();
            } else {
                filter_list = [$('#group_list').val()];
            }
            var map;
            user_jqgrid.getData({filter_type: filter_type, filter_list: filter_list}, function (l) {
                map = mkmap(l, 'id');
                var list = [];
                $.each(l, function (k, v) {
                    v.action = '<a href="javascript:;" class="btn-ignore" data-id="' + v.id + '">忽略</a>';
                    list.push(v);
                });
                return list;
            }).on('hxop.jqgrid-show', function () {
                $("#user-list .btn-ignore").on('click', function () {

                    var id = $(this).data('id');
                    if (id in selected_user_map) return;
                    selected_user_map[id] = {
                        name: map[id].real_name,
                        value: id
                    };

                    resetUser();
                });
            });
        });
        $('#reward-search-btn').on('click', function () {
            var keyword = $('#reward-keyword').val();
            if (!keyword) {
                alert('请输入关键字查询');
                return;
            }
            reward_jqgrid.getData({keyword: keyword}, function (l) {
                var list = [];
                $.each(l, function (k, v) {
                    var d = {};
                    d.name = v.name;
                    d.behavior = '<select class="behavior-select" data-id="' + v.id + '"></select>';
                    d.action = '<a class="add-reward-btn" data-id="' + v.id + '">添加</a>';
                    d.reward = '';


                    $.each(v.items.cash_voucher_list, function (k1, v1) {
                        d.reward += v1.name + ','
                    });
                    $.each(v.items.rate_increment_voucher_list, function (k1, v1) {
                        d.reward += v1.name + ','
                    });
                    $.each(v.items.red_packet_list, function (k1, v1) {
                        d.reward += v1.name + ','
                    });
                    d.reward = d.reward.substr(0, d.reward.length - 1);
                    list.push(d);
                });
                return list;
            }).off().on('hxop.jqgrid-show', function () {
                var s = '';
                $.each(behavior_list, function (k, v) {
                    s += '<option value="' + v.value + '">' + v.name + '</option>';
                });
                $('.behavior-select').html(s);
                $('.add-reward-btn').on('click', function () {
                    var row = $(this).parents('tr');
                    var id = $(this).data('id');
                    var behavior = $('.behavior-select', row).val();
                    if (id in select_reward_map) {
                        return;
                    }
                    var name = row.children().first().html();
                    var value = id + ',' + behavior;
                    select_reward_map[id] = {
                        name: name,
                        value: value
                    };
                    resetReward();
                });
            });
        });
    });

</script>
@endsection
